package net.tavion.angelboot.common.head;

import net.tavion.angelboot.common.utils.GenerateIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;

/**
 * @author yuzhou
 * @date 2017年6月30日
 * @time 下午4:13:22
 *
 */
public class RequestHeadDataHolder {

    private static final Logger logger = LoggerFactory.getLogger(RequestHeadDataHolder.class);

    private static final ThreadLocal<RequestHeadData> REQUEST_HEAD_DATA_HOLDER = new NamedThreadLocal<RequestHeadData>("RequestHeadDataHolder"){
        @Override
        protected RequestHeadData initialValue() {
            return new RequestHeadData();
        }
    };
 
    public static RequestHeadData getRequestHeadData() {
        return REQUEST_HEAD_DATA_HOLDER.get();
    }
    
    public static void setRequestHeadData(RequestHeadData pulicData) {
        REQUEST_HEAD_DATA_HOLDER.set(pulicData);
        if(logger.isDebugEnabled()) {
            logger.debug("set public data {}",pulicData);
        }
    }

    public static void initRequestData(){
        String requestId  = getRequestHeadData().getRequestId();
        if(StringUtils.isBlank(requestId)){
           getRequestHeadData().setRequestId(GenerateIdUtils.generateRequestId());
        }

    }
    
    public static void clear() {
        REQUEST_HEAD_DATA_HOLDER.remove();
    }
    
}
